package de.gwtprime.server.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;

import de.gwtprime.shared.util.AppUtilsShared;

/**
 * Provide login via social media sites like facebook
 * @author jan
 *
 */
public class SocialAuthServlet extends LoginSuperServlet{

	/**
	 * Serial ID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(LoginGoogleCallbackServlet.class.getName());

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//Create an instance of SocialAuthConfgi object
		SocialAuthConfig config = SocialAuthConfig.getDefault();

		try {
			//load configuration. By default load the configuration from oauth_consumer.properties. 
			//You can also pass input stream, properties object or properties file name.
			config.load();

			//Create an instance of SocialAuthManager and set config
			SocialAuthManager manager = new SocialAuthManager();
			manager.setSocialAuthConfig(config);


			//URL of YOUR application which will be called after authentication
			String successUrl = AppUtilsShared.DOMAIN_PROD+"socialauthCallback";

			// get Provider URL to which you should redirect for authentication.
			// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
			String url = manager.getAuthenticationUrl("facebook", successUrl);

			HttpSession session = request.getSession();
			// Store in session
			session.setAttribute("authManager", manager);
			
			storeLastPageToSession(request);
			
			resp.sendRedirect(url);
		} catch (Exception e) {
			logger.error(e);
			resp.getWriter().println(e);
		}
	}
}
